package cc.mycraft.pvp;

import java.io.File;
import java.util.Arrays;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class ArenaShop {
	private static File ItemFile;
	private static FileConfiguration Item;
	
	public static void run() {
		ItemFile = new File(Main.getPlugin().getDataFolder()+"/shop.yml");
		Item = YamlConfiguration.loadConfiguration(ItemFile);
	}
	
	public static void addItem(Player p,String price) {
		int priceInt = Integer.parseInt(price);
		ItemStack i = p.getItemInHand();
		int amount = Item.getInt("Amount")+1;
		Item.set("Amount", amount);
		Item.set("Shop."+amount+".Price", priceInt);
		Item.set("Shop."+amount+".Item", i);
		p.sendMessage("已添加到"+amount+"号物品");
		try {
			Item.save(ItemFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void buyItem(Player p,String number) {
		int price = Item.getInt("Shop."+number+".Price");
		int point = PlayerManager.getPoint(p);
		if(point<price) {
			ActionBar bar = new ActionBar("§e积分不足，你只有"+point+"分，不能买这件物品。");
			bar.send(p);
			return;
		}
		if(!hasAvaliableSlot(p, 1)) {
			ActionBar bar = new ActionBar("§e你的背包空间不够，请腾出1格背包空间再购买物品。");
			bar.send(p);
			return;
		}
		PlayerManager.subPoint(p, price);
		ItemStack i = Item.getItemStack("Shop."+number+".Item");
		p.getInventory().addItem(i);
		ActionBar bar = new ActionBar("§6购买成功！你的积分剩余：§e"+(point-price)+"§c(-"+price+")");
		bar.send(p);
	}
	
	public static boolean hasAvaliableSlot(Player player, int howmanyclear) {
		int check = 0;
		ItemStack is[] = player.getInventory().getContents();
		for (int i = 0; i < 36; i++) {
			if (is[i] == null) {
				check++;
			}
		}
		if (check >= howmanyclear) {
			return true;
		} else {
			return false;
		}
	}
}
